package com.hsy.order.setting.action

import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import com.flux.action.SubscriptionManager
import com.flux.dispatcher.Dispatcher
import com.hsy.order.base.action.ActionType
import com.hsy.order.base.action.BaseActionCreator
import com.hsy.order.base.action.BaseParam
import com.hsy.order.base.action.Key
import com.hsy.order.base.http.RetrofitFactory

/**
 * 首页行为生成器
 * Created on 2017/12/4.
 *
 * @author Yang
 */
class SettingActionCreator(dispatcher: Dispatcher, manager: SubscriptionManager) : BaseActionCreator(dispatcher, manager) {

    private val service = RetrofitFactory.getService(SettingService::class.java)

    /**
     * 获取用户信息
     */
    fun getUerInfo() {
        val action = newAction(ActionType.GET_USER_INFO)

        val params = BaseParam()
        service.getUerInfo(params.toMap())
                .subscribeOn(Schedulers.io())
                .filter { response -> checkResult(response.error, "0", response.msg) }
                .map { response -> response.result }
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({ userInfo ->
                    action.data[Key.USER_INFO] = userInfo
                    postRxAction(action)
                }, { throwable ->
                    handleHttpError(throwable)
                    action.success = false
                    postRxAction(action)
                })
    }

    /**
     * 获取用户信息
     */
    fun setShop(key: String, value: String) {
        val action = newAction(ActionType.SET_SHOP)

        val params = SettingParam(key, value)
        service.setShop(params.toMap())
                .subscribeOn(Schedulers.io())
                .filter { response -> checkResult(response.error, "0", response.msg) }
                .map { response -> response.result }
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({ userInfo ->
                    action.data[Key.USER_INFO] = userInfo
                    postRxAction(action)
                }, { throwable ->
                    handleHttpError(throwable)
                    action.success = false
                    postRxAction(action)
                })
    }
}